import { ref, reactive, computed, onMounted } from 'vue'
import { defineStore } from 'pinia'
import { baseURL } from '@/utils/request'
// 播放器状态存储键
const PLAYER_STATE_KEY = 'music_player_state'

export const usePlayerStore = defineStore('player', () => {
  // 当前播放歌曲
  const currentSong = reactive({
    id: null,
    name: '',
    artist: '',
    coverUrl: '',
    url: '',
    isVip: false,
    album: '',
    isFavorite: 0
  })

  // 播放状态
  const isPlaying = ref(false)
  
  // 播放列表
  const playlist = ref([])
  
  // 当前在播放列表中的索引
  const currentIndex = ref(-1)
  
  // 循环模式: 0-列表循环，1-单曲循环，2-随机播放
  const playMode = ref(0)
  
  // 是否循环播放
  const isLoop = ref(false)
  
  // 计算属性：当前播放歌曲是否被喜欢
  const isCurrentLiked = computed(() => {
    return currentSong.id ? currentSong.isFavorite === 1 : false
  })
  
  // 确保刷新页面后为暂停状态
  function ensurePaused() {
    // 页面加载后，确保播放器处于暂停状态
    isPlaying.value = false
  }
  
  // 播放歌曲
  function playSong(song) {
    // 更新歌曲信息
    currentSong.id = song.songId
    currentSong.name = song.songName
    currentSong.artist = song.artist
    
    // 确保URL包含完整路径
    currentSong.coverUrl = song.coverUrl && song.coverUrl.startsWith('http') 
      ? song.coverUrl 
      : song.coverUrl ? `${baseURL}${song.coverUrl}` : ''
    
    currentSong.url = song.musicUrl && song.musicUrl.startsWith('http') 
      ? song.musicUrl 
      : song.musicUrl ? `${baseURL}${song.musicUrl}` : ''
    
    currentSong.album = song.album
    currentSong.isVip = false // 可以根据需要设置
    currentSong.isFavorite = song.isLiked ? 1 : 0
    
    // 设置为播放状态
    isPlaying.value = true
    
    // 查找并更新当前播放索引
    updateCurrentIndex(song.songId)
  }
  
  // 更新当前播放索引
  function updateCurrentIndex(songId) {
    const index = playlist.value.findIndex(item => item.id === songId)
    if (index !== -1) {
      currentIndex.value = index
    }
  }
  
  // 播放/暂停切换
  function togglePlay() {
    isPlaying.value = !isPlaying.value
  }
  
  // 停止播放
  function stopPlay() {
    isPlaying.value = false
  }
  
  // 播放下一首
  function playNext() {
    if (!playlist.value || playlist.value.length === 0 || !currentSong.id) {
      return
    }

    const currentIndex = playlist.value.findIndex(song => song.id === currentSong.id)
    let nextIndex = 0

    // 根据播放模式确定下一首歌
    if (playMode.value === 2) {
      // 随机模式
      nextIndex = Math.floor(Math.random() * playlist.value.length)
    } else {
      // 列表循环模式
      nextIndex = (currentIndex + 1) % playlist.value.length
    }

    const nextSong = playlist.value[nextIndex]
    if (nextSong) {
      playSong({
        songId: nextSong.id,
        songName: nextSong.title,
        artist: nextSong.artist,
        coverUrl: nextSong.coverUrl,
        musicUrl: nextSong.musicUrl,
        album: nextSong.album,
        isLiked: nextSong.isFavorite === 1
      })
    }
  }
  
  // 播放上一首
  function playPrevious() {
    if (!playlist.value || playlist.value.length === 0 || !currentSong.id) {
      return
    }

    const currentIndex = playlist.value.findIndex(song => song.id === currentSong.id)
    let prevIndex = 0

    // 根据播放模式确定上一首歌
    if (playMode.value === 2) {
      // 随机模式
      prevIndex = Math.floor(Math.random() * playlist.value.length)
    } else {
      // 列表循环模式
      prevIndex = (currentIndex - 1 + playlist.value.length) % playlist.value.length
    }

    const prevSong = playlist.value[prevIndex]
    if (prevSong) {
      playSong({
        songId: prevSong.id,
        songName: prevSong.title,
        artist: prevSong.artist,
        coverUrl: prevSong.coverUrl,
        musicUrl: prevSong.musicUrl,
        album: prevSong.album,
        isLiked: prevSong.isFavorite === 1
      })
    }
  }
  
  // 设置播放列表
  function setPlaylist(songs) {
    playlist.value = songs
  }
  
  // 添加歌曲到播放列表
  function addToPlaylist(song) {
    const exists = playlist.value.some(item => item.id === song.id)
    if (!exists) {
      playlist.value.push(song)
    }
  }
  
  // 移除歌曲从播放列表
  function removeFromPlaylist(songId) {
    const index = playlist.value.findIndex(item => item.id === songId)
    if (index !== -1) {
      playlist.value.splice(index, 1)
      
      // 如果删除的是当前播放的歌曲，播放下一首
      if (songId === currentSong.id) {
        playNext()
      }
      // 更新currentIndex
      if (currentIndex.value > index) {
        currentIndex.value--
      }
    }
  }
  
  // 切换循环播放
  function toggleLoop() {
    isLoop.value = !isLoop.value
  }
  
  return {
    currentSong,
    isPlaying,
    playlist,
    currentIndex,
    playMode,
    isLoop,
    isCurrentLiked,
    playSong,
    togglePlay,
    stopPlay,
    playNext,
    playPrevious,
    setPlaylist,
    addToPlaylist,
    removeFromPlaylist,
    toggleLoop,
    ensurePaused
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'music-player',
        storage: localStorage,
        paths: ['currentSong', 'playMode', 'isLoop'] // 移除isPlaying，确保总是从暂停状态开始
      }
    ]
  }
}) 